﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using DevExpress.Web.ASPxClasses.Internal;
using System.Web.Caching;
using ZX.EHR.Library;
using System.Data;
using ZX.DAL.DBExtend;
using ZX.BLL.Extend;

namespace ZX.WebApp.EHR
{
    public partial class hrUpLoadAfterTaxDebit : BasePage
    {
        static string resFileName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            if (resFileName != "") this.SaveAfterTaxDebitData();
        }

        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            try
            {
                if (!uploadedFile.IsValid)
                    return string.Empty;

                FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
                string path = Request.PhysicalApplicationPath + "upload/EHR/";
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                resFileName = path + fileInfo.Name;
                uploadedFile.SaveAs(resFileName);
                RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);
                string fileLabel = fileInfo.Name;
                string fileLength = uploadedFile.ContentLength / 1024 + "K";
                return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
            }
            catch (Exception ex)
            {
                try
                {
                    salSalarylErrorLog salaryErrLog = new salSalarylErrorLog();
                    ZX.BLL.Extend.BaseBussnies errBll = new ZX.BLL.Extend.BaseBussnies(salaryErrLog);
                    salaryErrLog.moduleName = this.GetType().Module.Name;
                    salaryErrLog.className = this.GetType().Name;
                    salaryErrLog.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    salaryErrLog.errMsg = ex.Message;
                    salaryErrLog.errDate = DateTime.Now;
                    errBll.Insert();
                }
                catch { }
                throw ex;
            }
        }



        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }
        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        /// <summary>
        /// 保存薪资数据
        /// </summary>
        protected void SaveAfterTaxDebitData()
        {
            try
            {
                //读取EXCEL
                if (resFileName != "")
                {
                    DataTable dtExcel = DbSql.ReadEcxel(resFileName, 1);
                    if (dtExcel == null || dtExcel.Rows.Count == 0)
                    {
                        HttpContext.Current.Response.Write("1");
                        return;
                    }
                    salAfterTaxDebit instance = new salAfterTaxDebit();
                    BaseBussnies baseSalaryBll = new BaseBussnies(instance);
                    foreach (DataRow dr in dtExcel.Rows)
                    {
                        string empCode = dr["员工编号"].ToString().Trim();
                        if (empCode == "") continue;
                        string beiYongJin = dr["备用金"].ToString().Trim();
                        string caiLing = dr["彩铃"].ToString().Trim();
                        string daiKouSheBao = dr["代扣社保"].ToString().Trim();
                        string daiKouGongJiJin = dr["代扣公积金"].ToString().Trim();
                        string qiTaKouKuan1 = dr["其他扣款1"].ToString().Trim();
                        string qiTaKouKuan2 = dr["其他扣款2"].ToString().Trim();
                        string qiTaKouKuan3 = dr["其他扣款3"].ToString().Trim();
                        string qiTaKouKuanDes1 = dr["其他扣款1说明"].ToString().Trim();
                        string qiTaKouKuanDes2 = dr["其他扣款2说明"].ToString().Trim();
                        string qiTaKouKuanDes3 = dr["其他扣款3说明"].ToString().Trim();
                        string year = dr["年"].ToString().Trim();
                        string month = dr["月"].ToString().Trim();
                        int yy = -1, mm = -1;
                        Int32.TryParse(year, out yy);
                        Int32.TryParse(month, out mm);
                        if (yy == -1 || mm == -1) continue;
                        //获取empId
                        hrEmployee employee = new hrEmployee();
                        ZX.BLL.Extend.BaseBussnies empBll = new BaseBussnies(employee);
                        employee = empBll.GetEntityByCondition("EmployeeCode='" + empCode + "'") as hrEmployee;
                        if (employee == null) continue;
                        string empId = employee.ID.ToString();
                        instance = baseSalaryBll.GetEntityByCondition("EmployeeID='" + empId + "' and year=" + year + " and month=" + month) as salAfterTaxDebit;
                        decimal sa1 = 0, sa2 = 0, sa3 = 0, sa4 = 0, sa5 = 0, sa6 = 0, sa7 = 0;
                        decimal.TryParse(beiYongJin, out sa1);
                        decimal.TryParse(caiLing, out sa2);
                        decimal.TryParse(daiKouSheBao, out sa3);
                        decimal.TryParse(daiKouGongJiJin, out sa4);
                        decimal.TryParse(qiTaKouKuan1, out sa5);
                        decimal.TryParse(qiTaKouKuan2, out sa6);
                        decimal.TryParse(qiTaKouKuan3, out sa7);
                        if (instance == null) //不存在该员工数据
                        {
                            instance = new salAfterTaxDebit();
                            instance.ID = Guid.NewGuid();
                            instance.EmployeeID = new Guid(empId);
                            instance.beiYongJin = sa1;
                            instance.caiLing = sa2;
                            instance.daiKouSheBao = sa3;
                            instance.daiKouGongJiJin = sa4;
                            instance.qiTaKouKuan1 = sa5;
                            instance.qiTaKouKuan2 = sa6;
                            instance.qiTaKouKuan3 = sa7;
                            instance.qiTaKouKuanDes1 = qiTaKouKuanDes1;
                            instance.qiTaKouKuanDes2 = qiTaKouKuanDes2;
                            instance.qiTaKouKuanDes3 = qiTaKouKuanDes3;
                            instance.year = yy;
                            instance.month = mm;
                            instance.AddTime = DateTime.Now;
                            instance.AddUser = this.UserId.Value;
                            baseSalaryBll.Insert(instance);
                        }
                        else
                        {
                            instance.beiYongJin = sa1;
                            instance.caiLing = sa2;
                            instance.daiKouSheBao = sa3;
                            instance.daiKouGongJiJin = sa4;
                            instance.qiTaKouKuan1 = sa5;
                            instance.qiTaKouKuan2 = sa6;
                            instance.qiTaKouKuan3 = sa7;
                            instance.qiTaKouKuanDes1 = qiTaKouKuanDes1;
                            instance.qiTaKouKuanDes2 = qiTaKouKuanDes2;
                            instance.qiTaKouKuanDes3 = qiTaKouKuanDes3;
                            instance.year = yy;
                            instance.month = mm;
                            instance.AddTime = DateTime.Now;
                            instance.AddUser = this.UserId.Value;
                            baseSalaryBll.Update(instance);
                        }
                    }
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("2");//文件未上传
                }
                if (System.IO.File.Exists(resFileName))
                {
                    System.IO.File.Delete(resFileName);
                }
                resFileName = "";
            }
            catch (Exception ex)
            {
                try
                {
                    salSalarylErrorLog salaryErrLog = new salSalarylErrorLog();
                    ZX.BLL.Extend.BaseBussnies errBll = new ZX.BLL.Extend.BaseBussnies(salaryErrLog);
                    salaryErrLog.moduleName = this.GetType().Module.Name;
                    salaryErrLog.className = this.GetType().Name;
                    salaryErrLog.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    salaryErrLog.errMsg = ex.Message;
                    salaryErrLog.errDate = DateTime.Now;
                    errBll.Insert();
                }
                catch { }
                HttpContext.Current.Response.Write("0");
            } 
        }
    }
}